import { Injectable } from "@angular/core";
import { HttpService, HTTPMethods, APIPath } from "http-service";
import { SqliteService } from "./sqliteDB/sqlite.service";
import {SecureStorageService} from './secure-storage.services';
import { Platform } from 'ionic-angular';
import {API} from "../models/api-path-extension";
import { LogonService } from "./logon.services";

declare var window: {
  localStorage: {
    removeItem: any
  }
};

declare let navigator: any;

@Injectable()
export class RefreshTokenService {

  constructor(
    private secureStorageService: SecureStorageService,
    private logonService: LogonService,
    private sqliteService: SqliteService,
    private httpService: HttpService) {
  }

  refreshToken(timeout = 1) {
    return this.secureStorageService.get("refresh_token")
      .flatMap((refreshToken) => {
        return this.httpService.fetchWithPath(
          new API().path({path: "refreshToken", method: HTTPMethods.Post}),
          {
            grant_type: "refresh_token",
            refresh_token: refreshToken
          }, null , {
            'Content-Type': 'application/x-www-form-urlencoded',
            "Authorization": "Basic YXBwOmFwcA==",
            "timeout": timeout
          })
          .map((data) => {
            this.secureStorageService.set("access_token", data["access_token"]);
            this.secureStorageService.set('refresh_token', data["refresh_token"]);
            return data;
          });
          // .catch((error) => {
          //   return this.logonService.loginVPN()
          //     .map((data) => {
          //       this.refreshToken();
          //       return data;
          //     })
          //     .catch((e) => {
          //       this.sqliteService.dropDataBase();
          //     });
          //   // return error;
          // });
    });

  }

}
